<template>
  <div class="data-dashboard">
    <h2>历史数据</h2>

    <button @click="fetchAllData" class="fetch-all-btn">
      获取所有传感器数据
    </button>

    <div class="sensor-data-container">
      <div
          v-for="(sensor, index) in sensors"
          :key="index"
          class="sensor-data"
      >
        <h3>{{ sensor.label }}</h3>

        <!-- 表格: 显示名称/值/单位/时间 -->
        <table class="history-data-table">
          <thead>
          <tr>
            <th>名称</th>
            <th>值</th>
            <th>单位</th>
            <th>时间</th>
          </tr>
          </thead>
          <tbody>
          <tr
              v-for="(row, rowIndex) in sensor.historyData"
              :key="rowIndex"
          >
            <td>{{ row.name }}</td>
            <td>{{ row.value }}</td>
            <td>{{ row.unit }}</td>
            <td>{{ formatTime(row.createdTime) }}</td>
          </tr>
          </tbody>
        </table>

      </div>
    </div>
  </div>
</template>

<script>
import { fetchHistoryData, fetchAndSaveData } from '../utils/api';
import LineChart from './LineChart.vue';

export default {
  name: 'DataDashboard',
  components: { LineChart },
  data() {
    return {
      sensors: [
        {
          label: '二氧化碳含量',
          type: 'CarbonDioxide',
          boxNo: '300023040198',
          latestData: null,
          historyData: []
        },
        {
          label: '土壤氮含量',
          type: 'Nitrogen',
          boxNo: '300023040198',
          latestData: null,
          historyData: []
        },
        {
          label: '土壤磷含量',
          type: 'Phosphorus',
          boxNo: '300023040198',
          latestData: null,
          historyData: []
        },
        {
          label: '土壤钾含量',
          type: 'Potassium',
          boxNo: '300023040198',
          latestData: null,
          historyData: []
        },
        {
          label: '光照传感器',
          type: 'Light',
          boxNo: '300023040198',
          latestData: null,
          historyData: []
        }
      ]
    };
  },
  methods: {
    /**
     * 将后端返回的“原始数据”转换成统一格式:
     * {
     *   name: string,
     *   value: number,
     *   unit: string,
     *   createdTime: string (或可被Date解析的格式)
     * }
     */
    transformRawData(rawData) {
      return rawData.map(item => {
        // 若有些后端返回的是字符串，转为数字
        let numericValue = item.value;
        if (typeof numericValue === 'string') {
          numericValue = parseFloat(numericValue);
        }
        // 如果拿到 null 或空，就给个默认0
        if (!numericValue) {
          numericValue = 0;
        }


        let isoTime = item.createdTime || '';
        if (isoTime.indexOf(' ') === 10) {

          isoTime = isoTime.replace(' ', 'T');
        }

        return {
          name: item.name || '未知名称',
          value: numericValue,
          unit: item.unit || '',
          createdTime: isoTime
        };
      });
    },

    /**
     * 获取单个传感器数据并保存到 sensor.historyData
     */
    async fetchSensorData(sensor) {
      try {
        const response = await fetchHistoryData(sensor.type);
        if (response && response.data) {
          let formatted = this.transformRawData(response.data);

          formatted.sort((a, b) => new Date(b.createdTime) - new Date(a.createdTime));

          sensor.historyData = formatted.slice(0, 3);

          sensor.latestData = sensor.historyData[0];
        }
      } catch (error) {
        console.error(`获取 ${sensor.label} 历史数据失败:`, error);
      }
    },

    /**
     * 一键获取所有传感器数据
     */
    async fetchAllData() {
      try {
        for (const sensor of this.sensors) {
          await fetchAndSaveData(sensor.type, sensor.boxNo);

          await this.fetchSensorData(sensor);
        }
      } catch (error) {
        console.error('获取所有传感器数据失败:', error);
      }
    },

    formatTime(timeStr) {
      if (!timeStr) return '无';
      const date = new Date(timeStr);
      // 转成本地时间
      return date.toLocaleString();
    }
  },
  mounted() {
    this.sensors.forEach(sensor => this.fetchSensorData(sensor));
  }
};
</script>

<style scoped>
.data-dashboard {
  margin: 20px;
}
.fetch-all-btn {
  margin-bottom: 20px;
  padding: 10px 20px;
  background-color: #28a745;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}
.fetch-all-btn:hover {
  background-color: #218838;
}
.sensor-data-container {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  gap: 20px;
}
.sensor-data {
  flex: 1 1 calc(33.33% - 20px);
  border: 1px solid #ddd;
  padding: 15px;
  border-radius: 5px;
  background-color: #f9f9f9;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}
.history-data-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 10px;
}
.history-data-table th,
.history-data-table td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}
.history-data-table th {
  background-color: #f4f4f4;
}
</style>
